package com.betty.contacttest01;

import android.app.Activity;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    final int REQUEST_CODE=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn=(Button)findViewById(R.id.btn_query);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setAction(intent.ACTION_GET_CONTENT);
                intent.setType("vnd.android.cursor.item/phone");
                startActivityForResult(intent,REQUEST_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK){
//            获取返回数据
            Uri contactData=data.getData();
            CursorLoader cursorLoader=new CursorLoader(this,contactData,null,null,null,null);
//            查询联系人姓名
            Cursor cursor=cursorLoader.loadInBackground();
            if (cursor.moveToFirst()){
                String contact_ID=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//                获取联系人姓名
                String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                String phoneNumber = "No phone Number";
                Cursor phone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.Contacts._ID+"="+contact_ID,null,null);
                if (phone.moveToFirst()){
//                    提取电话号码
                    phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
//                关闭游标
                phone.close();
                EditText et_name = (EditText)findViewById(R.id.et_name);
                et_name.setText(name);
                EditText et_number = (EditText)findViewById(R.id.et_number);
                et_number.setText(phoneNumber);
            }
            cursor.close();
        }
    }
}
